import { useEffect } from 'react'
import { IS_DEV } from '@/library/tool-kits/get-process-env'
import { isFunction } from '@/library/tool-kits/is-valid'
import { useLatest } from './use-latest'

interface UseUnmount {
  (fn: () => void): void
}

export const useUnmount: UseUnmount = (fn) => {
  if (IS_DEV && !isFunction(fn)) {
    console.error('useUnmount expected parameter is a function, got '.concat(typeof fn))
  }

  const fnRef = useLatest(fn)

  useEffect(() => () => fnRef.current(), [])
}
